// @ts-nocheck
import * as XLSX from 'xlsx'

// 以二进制方式打开文件
function getReadFile (file: File, tableName: string) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.readAsArrayBuffer(file)
    fileReader.onload = function (ev: any) {
      try {
        const data = XLSX.read(ev.target.result, {
          type: 'binary'
        }) // 以二进制流方式读取得到整份excel表格对象
        const tableData = data.Sheets[tableName]
        resolve(tableData)
      } catch (e) {
        reject(e)
      }
    }
  })
}
// 获取坐标
function getLocation (str: string): number[] {
  const index = str.search(/[0-9]/)
  const col = stringTranNumber(str.substring(0, index))
  const row = Number(str.substring(index, str.length)) - 1
  return [col, row]
}

// 获取所在列数
function stringTranNumber (str: string): number {
  const a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = 0
  let index = 1
  for (const i of str) {
    result = (a.indexOf(i) + 1) * Math.pow(26, str.length - index) + result
    index++
  }
  return result - 1
}

// 删除坐标
function delLocation (obj: []) {
  obj.map((i: any) => {
    delete i.e
    delete i.s
    if (i.children) {
      delLocation(i.children)
    }
  })
}

export default async function getData (file: File, tableName: string, begin: string, finish: string) {
  // 读取文件内容
  const data: any = await getReadFile(file, tableName)
  console.log(data)
  // 对文件内容进行数据加工、筛选
  // const obj: Record<string, any> = {}
  // const keylist: any[] = []
  const readFileFilter: any[] = []
  for (const key in data) {
    if (Number(key.charAt(key.length - 1))) {
      // obj[key] = data[key]
      // keylist.push(key)
      const obj = {
        location: getLocation(key)
      }
      Object.assign(obj, data[key])
      readFileFilter.push(obj)
    }
  }
  const beginLocation = getLocation(begin)
  const finishLocation = getLocation(finish)
  const readDataMach = readFileFilter.filter(i => beginLocation[0] <= i.location[0] && i.location[0] <= finishLocation[0] &&
   beginLocation[1] <= i.location[1] && i.location[1] <= finishLocation[1])
  readDataMach.map(i => {
    const map = data['!merges']?.find((item: { s: { c: number; r: number }, e: any }) => item.s.c === i.location[0] &&
    item.s.r === i.location[1])
    if (map) {
      return Object.assign(i, map)
    } else {
      return Object.assign(i, { s: { c: i.location[0], r: i.location[1] }, e: { c: i.location[0], r: i.location[1] } })
    }
  })
  console.log(readDataMach)
  const dataLayered = []
  for (let i = beginLocation[1]; i <= finishLocation[1]; i++) {
    dataLayered.push(readDataMach.filter(item => item.location[1] === i))
  }
  console.log(dataLayered)

  // 开始组建json对象
  const dataList: any = [[]]
  dataLayered.filter(i => i.length > 0).reverse().map((val, index, arr) => {
    if (index === 0) {
      val.map(item => {
        dataList[index].push({
          s: item.s,
          e: item.e,
          label: item.v,
          align: 'center',
          minWidth: '',
          prop: ''
        })
      })
    } else {
      val.map(item => {
        const list = dataList[index - 1].filter((a: any) => a.s.c >= item.s.c && a.e.c <= item.e.c)
        if (dataList[index]) {
          if (list.length) {
            dataList[index].push({
              s: item.s,
              e: item.e,
              label: item.v,
              align: 'center',
              children: list
            })
          } else {
            dataList[index].push({
              s: item.s,
              e: item.e,
              label: item.v,
              align: 'center',
              prop: ''
            })
          }
        } else {
          if (list.length) {
            dataList.push([{
              s: item.s,
              e: item.e,
              label: item.v,
              align: 'center',
              children: list
            }])
          } else {
            dataList.push([{
              s: item.s,
              e: item.e,
              label: item.v,
              align: 'center',
              prop: ''
            }])
          }
        }
      })
    }
  })

  // 删除多余属性（坐标）
  const result = dataList[dataList.length - 1]
  delLocation(result)
  console.log('finish:', result)
  return result
}
